package top.tangyh.lamp.test;

public class ByteToBits {
    public static void main(String[] args) {
        byte b = 0; // 例子中的字节值

        String bitString = byteToBits(b);
        System.out.println("Byte: " + b);
        System.out.println("Bits: " + bitString);
        System.out.println(byteToHex(b));
    }

    public static String byteToBits(byte b) {
        StringBuilder bits = new StringBuilder();
        for (int i = 7; i >= 0; i--) {
            // 按位与运算获取每一位的值，然后转换为字符 '0' 或 '1'
            bits.append((b >> i) & 1);
        }
        return bits.toString();
    }

    /**
     * 字节转十六进制
     * @param b 需要进行转换的byte字节
     * @return  转换后的Hex字符串
     */
    public static String byteToHex(byte b){
        String hex = Integer.toHexString(b & 0xFF);
        if(hex.length() < 2){
            hex = "0" + hex;
        }
        return hex;
    }
}
